<template>
  <div class="app-container">
    <el-card>
      <title-line title="新增弹窗" />
      <el-form ref="elForm" :model="formData" :rules="rules" label-width="100px">
        <el-row>
          <el-col :lg="16" :xl="10">
            <el-form-item label="弹窗名称：" prop="windowName">
              <el-input
                v-model="formData.windowName"
                placeholder="请输入弹窗名称（2-20个字）"
                clearable
              />
            </el-form-item>
            <el-form-item label="弹窗位置：" prop="windowPlaces">
              <el-checkbox-group v-model="formData.windowPlaces">
                <el-checkbox
                  v-for="(item, index) in POPUP_PLACE_LABEL"
                  :key="index"
                  :label="item.value"
                >
                  {{ item.label }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>

            <el-form-item label="弹窗图片：" prop="windowImg">
              <UploadImage
                :isShowTip="true"
                :file-type="['jpg', 'png', 'jpeg']"
                file-pixel="600*400"
                :file-size="1"
                :limit="1"
                @on-change="uploadChange"
                v-model="formData.windowImg"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :lg="16" :xl="14">
            <el-form-item label="指向位置：" prop="pointPlace">
              <PointPosition ref="PointPosition" v-model="formData" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :lg="16" :xl="10">
            <el-form-item label="投放时间：" prop="timeRule">
              <el-row>
                <el-col :lg="10" :xl="8">
                  <el-radio-group v-model="formData.timeRule">
                    <el-radio
                      v-for="(item, index) in APPOINT_TIME_STATUS"
                      :key="index"
                      :label="item.value"
                    >
                      {{ item.label }}
                    </el-radio>
                  </el-radio-group>
                </el-col>
                <el-col :lg="14" :xl="16">
                  <el-date-picker
                    v-if="!formData.timeRule"
                    type="datetimerange"
                    :picker-options="pickerOptions"
                    v-model="time"
                    format="yyyy-MM-dd HH:mm:ss"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    range-separator="至"
                    clearable
                  />
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item label="排序位置：" prop="sort">
              <el-input v-model="formData.sort" placeholder="请输入排序位置" clearable />
              <p style="color: #909399; font-size: 12px">数字越小排序越靠前</p>
            </el-form-item>

            <el-form-item label="出现频次" prop="frequencyRule" class="first-show">
              <el-radio-group v-model="day" style="width: 100%">
                <div v-for="item in POPUP_SHOW_LABEL" :key="item.value">
                  <el-radio :label="item.value">
                    {{ item.label }}
                    <div style="display: inline-block" v-if="day && item.value === day">
                      <el-input-number
                        v-model="formData.frequencyRule"
                        class="ml-10 mr-10"
                        :min="1"
                        :max="7"
                      />
                      <span>天出现1次</span>
                    </div>
                  </el-radio>
                </div>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="是否启用：" prop="isShow">
              <el-radio-group v-model="formData.isShow">
                <el-radio v-for="(item, index) in ENABLE_STATUS" :key="index" :label="item.value">
                  {{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item style="text-align: center">
          <el-button @click="resetForm"> 取消 </el-button>
          <el-button type="primary" @click="submitForm"> 确定 </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import addrules from './rules'
import { parseTime } from '@/hooks'
import { PointPosition } from '@components'
import {
  APPOINT_TIME_STATUS,
  ENABLE_STATUS,
  POPUP_PLACE_LABEL,
  POPUP_SHOW_LABEL,
  REGION_TYPE
} from '@/enum/advert'
import { useValidatepointPlace } from '@/hooks'
export default {
  name: 'AddDialogPopup',
  components: {
    PointPosition
  },
  props: {
    title: {
      type: String,
      default: ''
    },
    type: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      checkAll: false,
      dialogVisible: false,
      formData: {
        sort: 99,
        windowName: '',
        pointPlace: 0,
        targetParam: '',
        timeRule: 1,
        isShow: true,
        windowImg: '',
        windowPlaces: [],
        frequencyRule: 0
      },
      day: 0,
      time: [],
      advertPlaceList: [],
      listQuery: {
        pageNo: 1,
        pageSize: 10
      },
      cityList: [],
      cityIdList: [],
      showRegion: true,
      // 选择开始时间大于等于当前时间
      pickerOptions: {
        disabledDate(time) {
          const dateTime = new Date()
          const startDateTime = dateTime.setDate(dateTime.getDate() - 1)
          const endDateTime = dateTime.setDate(dateTime.getDate() + 30000) //30000为当前日期之后多少天
          return (
            time.getTime() < new Date(startDateTime).getTime() ||
            time.getTime() > new Date(endDateTime).getTime()
          )
        },
        selectableRange:
          //setMinutes,getMinutes限制分 , 年、月、日、时、分、秒同理,+1为数字区间
          parseTime(new Date().setMinutes(new Date().getMinutes() + 1), '{hh}:{ii}:{ss}') +
          '- 23:59:00'
      }
    }
  },
  computed: {
    rules() {
      return {
        windowName: [
          {
            required: true,
            message: '请输入弹窗名称',
            trigger: 'blur'
          },
          {
            min: 2,
            max: 20,
            message: '弹窗名称限制2-20个字'
          }
        ],
        ...addrules
      }
    },
    REGION_TYPE() {
      return REGION_TYPE
    },
    ENABLE_STATUS() {
      return ENABLE_STATUS
    },
    APPOINT_TIME_STATUS() {
      return APPOINT_TIME_STATUS
    },
    POPUP_PLACE_LABEL() {
      return POPUP_PLACE_LABEL
    },
    POPUP_SHOW_LABEL() {
      return POPUP_SHOW_LABEL
    },
    id() {
      return this.$route.query?.id
    }
  },
  watch: {
    'formData.timeRule'(val) {
      if (val) {
        this.time = []
      }
    }
  },
  created() {
    this.getPopupList()
    this.getPopupDetail()
  },
  methods: {
    // 获取广告位置
    async getPopupList() {
      const params = {
        ...this.listQuery
      }
      const {
        data: { list }
      } = await this.$http.advert.popupApi.getPopupList({ params })
      this.advertPlaceList = list
    },
    // 校验指向时间
    validatepointTime() {
      const timeStart = this.time && this.time[0]
      const timeEnd = this.time && this.time[1]
      if (!(timeStart && timeEnd) && !this.formData.timeRule) {
        this.$message.error('请选择投放时间！')
        return false
      }

      let flag

      const start_date = this.$moment(timeStart, 'YYYY-MM-DD HH:mm:ss')
      const end_date = this.$moment(timeEnd, 'YYYY-MM-DD HH:mm:ss')
      const hours = end_date.diff(start_date, 'minutes')
      if (hours < 30) {
        this.$message.error('投放结束时间要大于投放开始时间半小时')
        flag = false
      } else {
        flag = true
      }
      return flag
    },
    // 获取参数
    getParams() {
      const params = {
        ...this.formData
      }
      if (!this.day) params.frequencyRule = 0
      if (this.id) params.id = this.id
      if (this.time) params.timeStart = this.time[0]
      if (this.time) params.timeEnd = this.time[1]
      if (params.windowPlaces) params.windowPlaces = params.windowPlaces.join(',')
      return params
    },
    // 获取详情
    async getPopupDetail() {
      if (!this.id) return
      const { data } = await this.$http.advert.popupApi.getPopupDetail(this.id)
      for (const key in this.formData) {
        if (key === 'pointPlace') {
          this.formData.pointPlace = parseInt(data[key])
        } else if (key === 'timeRule') {
          this.formData[key] = data[key] ? 1 : 0
        } else if (key === 'windowPlaces') {
          this.formData.windowPlaces = data[key]?.split(',').map(item => parseInt(item))
        } else {
          this.formData[key] = data[key]
        }
      }
      this.day = this.formData.frequencyRule ? 1 : 0
      this.$refs.PointPosition.loadPointData(this.formData)
      this.time = [data.timeStart ? data.timeStart : '', data.timeEnd ? data.timeEnd : '']
    },
    // 新增
    async addPopup() {
      const params = this.getParams()
      const { status, msg } = await this.$http.advert.popupApi.addPopup(params)
      if (status === 200) {
        this.$message.success('新增成功！')
        this.$router.back(-1)
      } else {
        this.$message.error(msg)
      }
    },
    // 编辑
    async updatePopup() {
      const params = this.getParams()
      const { status, msg } = await this.$http.advert.popupApi.updatePopup(params)
      if (status === 200) {
        this.$message.success('编辑成功！')
        this.$router.back(-1)
      } else {
        this.$message.error(msg)
      }
    },
    // 提交
    submitForm() {
      this.$refs['elForm'].validate(valid => {
        if (!valid) return

        // 校验指向位置
        let flag1 = useValidatepointPlace(this.formData)
        if (!flag1) return

        // 校验投放时间
        let flag2 = this.validatepointTime()
        if (!flag2) return
        if (this.day && !this.formData.frequencyRule) {
          this.$message.error('请输入每多少天出现次数')
          return
        }
        if (!this.id) {
          this.addPopup()
        } else {
          this.updatePopup()
        }
      })
    },
    uploadChange() {
      if (this.formData.windowImg) {
        this.$refs.elForm.validateField('windowImg')
      }
    },
    resetForm() {
      this.$refs['elForm'].resetFields()
      this.$router.back(-1)
    }
  }
}
</script>
<style lang="scss" scoped>
.first-show {
  /deep/ .el-radio {
    display: block;
    margin-bottom: 20px;
  }
}
</style>
